<template>
  <div class="customer-dashboard">
    <!-- 欢迎横幅 -->
    <el-card class="welcome-card" shadow="hover">
      <div class="welcome-content">
        <div class="welcome-text">
          <h2>欢迎回来，{{ userName }}！</h2>
          <p>您为环保事业贡献了 <span class="highlight">{{ totalContribution }}kg</span> 可回收物品</p>
        </div>
        <div class="welcome-action">
          <el-button 
            type="primary" 
            size="large" 
            @click="$router.push('/customer/create-order')"
          >
            <el-icon><Plus /></el-icon>
            创建新订单
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据统计卡片 -->
    <div class="stats-grid">
      <el-card class="stats-card" shadow="hover">
        <div class="stats-content">
          <div class="stats-icon orders">
            <el-icon size="28"><Document /></el-icon>
          </div>
          <div class="stats-info">
            <h3>{{ totalOrders }}</h3>
            <p>总订单数</p>
          </div>
        </div>
      </el-card>

      <el-card class="stats-card" shadow="hover">
        <div class="stats-content">
          <div class="stats-icon pending">
            <el-icon size="28"><Clock /></el-icon>
          </div>
          <div class="stats-info">
            <h3>{{ pendingOrders }}</h3>
            <p>进行中订单</p>
          </div>
        </div>
      </el-card>

      <el-card class="stats-card" shadow="hover">
        <div class="stats-content">
          <div class="stats-icon earnings">
            <el-icon size="28"><Money /></el-icon>
          </div>
          <div class="stats-info">
            <h3>¥{{ totalEarnings }}</h3>
            <p>累计收益</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 我的订单和回收物品价格 -->
    <div class="content-section">
      <el-row :gutter="24">
        <el-col :xs="24" :sm="24" :md="14" :lg="14" :xl="14">
          <el-card title="我的订单" shadow="hover" class="orders-card">
            <template #header>
              <div class="card-header">
                <span>我的订单</span>
                <el-button type="primary" size="small" @click="$router.push('/customer/orders')">
                  查看全部
                </el-button>
              </div>
            </template>
            <el-table :data="recentOrders" style="width: 100%" size="small" class="orders-table">
              <el-table-column prop="orderNo" label="订单号" min-width="130" />
              <el-table-column prop="stationName" label="回收站点" min-width="100" class-name="hide-on-mobile" />
              <el-table-column prop="pickupTime" label="预约时间" min-width="150" class-name="hide-on-tablet" />
              <el-table-column prop="totalAmount" label="金额" min-width="80">
                <template #default="scope">
                  <span>¥{{ scope.row.totalAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" min-width="80">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)" size="small">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="80" fixed="right">
                <template #default="scope">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="viewOrder(scope.row)"
                  >
                    查看
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="24" :md="10" :lg="10" :xl="10">
          <el-card title="今日回收价格" shadow="hover" class="price-card">
            <template #header>
              <div class="card-header">
                <span>今日回收价格</span>
                <el-button type="primary" size="small" @click="$router.push('/customer/browse')">
                  查看全部
                </el-button>
              </div>
            </template>
            <div class="price-list">
              <div 
                v-for="item in todayPrices" 
                :key="item.id" 
                class="price-item"
              >
                <div class="item-info">
                  <div class="item-name">{{ item.name }}</div>
                  <div class="item-category">{{ item.category }}</div>
                </div>
                <div class="item-price">
                  <span class="price">¥{{ item.price }}</span>
                  <span class="unit">/{{ item.unit }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 快捷操作和环保提示 -->
    <div class="bottom-section">
      <el-row :gutter="24">
        <el-col :xs="24" :sm="24" :md="14" :lg="14" :xl="14">
          <el-card title="快捷操作" shadow="hover" class="actions-card">
            <div class="quick-actions">
              <div class="action-item" @click="$router.push('/customer/browse')">
                <div class="action-icon browse">
                  <el-icon size="32"><Search /></el-icon>
                </div>
                <div class="action-text">
                  <h4>浏览物品</h4>
                  <p>查看可回收物品和价格</p>
                </div>
              </div>
              
              <div class="action-item" @click="$router.push('/customer/create-order')">
                <div class="action-icon create">
                  <el-icon size="32"><Plus /></el-icon>
                </div>
                <div class="action-text">
                  <h4>创建订单</h4>
                  <p>提交新的回收申请</p>
                </div>
              </div>
              
              <div class="action-item" @click="$router.push('/customer/orders')">
                <div class="action-icon track">
                  <el-icon size="32"><Location /></el-icon>
                </div>
                <div class="action-text">
                  <h4>订单跟踪</h4>
                  <p>查看订单处理进度</p>
                </div>
              </div>
              
              <div class="action-item" @click="$router.push('/customer/profile')">
                <div class="action-icon profile">
                  <el-icon size="32"><User /></el-icon>
                </div>
                <div class="action-text">
                  <h4>个人信息</h4>
                  <p>管理账户和设置</p>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="24" :md="10" :lg="10" :xl="10">
          <el-card title="环保小贴士" shadow="hover" class="tips-card">
            <div class="eco-tips">
              <div class="tip-item">
                <el-icon color="#67C23A" size="20"><Star /></el-icon>
                <span>将废纸分类整理，可以提高回收价值</span>
              </div>
              <div class="tip-item">
                <el-icon color="#409EFF" size="20"><Star /></el-icon>
                <span>塑料瓶清洗干净后回收，价格更高</span>
              </div>
              <div class="tip-item">
                <el-icon color="#E6A23C" size="20"><Star /></el-icon>
                <span>定期回收有助于获得更多环保积分</span>
              </div>
              <div class="tip-item">
                <el-icon color="#F56C6C" size="20"><Star /></el-icon>
                <span>电池等有害垃圾需要专门回收</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Plus,
  Document,
  Clock,
  Money,
  Search,
  Location,
  User,
  Star
} from '@element-plus/icons-vue'
import { ordersAPI, itemsAPI } from '@/api'

// 组件名称
defineOptions({
  name: 'CustomerDashboard'
})

const store = useStore()
const router = useRouter()

// 计算属性
const userName = computed(() => store.getters.userName)
const userId = computed(() => store.state.user?.id)

// 统计数据
const totalOrders = ref(0)
const pendingOrders = ref(0)
const totalEarnings = ref('0')
const totalContribution = ref(0)
const monthlyOrders = ref(0)

// 最近订单
const recentOrders = ref([])

// 今日价格
const todayPrices = ref([])

// 加载统计数据
const loadStats = async () => {
  try {
    const customerId = userId.value
    if (!customerId) {
      ElMessage.warning('用户信息不完整，请重新登录')
      return
    }

    // 获取所有订单来计算统计数据
    const response = await ordersAPI.getOrders({
      customerId,
      page: 1,
      pageSize: 1000 // 获取所有订单
    })

    const orderList = response.list || response.data || response || []
    
    // 计算统计数据
    totalOrders.value = orderList.length
    pendingOrders.value = orderList.filter(order => 
      order.status === 'pending' || order.status === 'confirmed' || order.status === 'in_progress'
    ).length
    
    // 计算总收益（只计算已完成的订单）
    const completedOrders = orderList.filter(order => order.status === 'completed')
    const revenue = completedOrders.reduce((sum, order) => {
      const amount = order.totalAmount || 0
      return sum + (typeof amount === 'number' ? amount : parseFloat(amount) || 0)
    }, 0)
    totalEarnings.value = revenue.toFixed(2)
    
    // 计算总贡献重量（从已完成订单的totalWeight字段计算）
    const totalWeight = completedOrders.reduce((sum, order) => {
      const weight = order.totalWeight || 0
      return sum + (typeof weight === 'number' ? weight : parseFloat(weight) || 0)
    }, 0)
    totalContribution.value = totalWeight.toFixed(1)
    
    // 计算本月新增订单
    const now = new Date()
    const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
    monthlyOrders.value = orderList.filter(order => {
      const orderDate = new Date(order.createTime)
      return orderDate >= firstDayOfMonth
    }).length
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  }
}

// 加载最近订单
const loadRecentOrders = async () => {
  try {
    const customerId = userId.value
    if (!customerId) return

    const response = await ordersAPI.getOrders({
      customerId,
      page: 1,
      pageSize: 3
    })

    const orderList = response.list || response.data || response || []
    
    recentOrders.value = orderList.map(order => ({
      id: order.id,
      orderNo: order.orderNo,
      stationName: order.stationName || order.station?.name || '未分配',
      pickupTime: formatDateTime(order.pickupTime),
      totalAmount: order.totalAmount || 0,
      status: order.status
    }))
  } catch (error) {
    console.error('加载订单列表失败:', error)
    ElMessage.error('加载订单列表失败')
  }
}

// 加载今日价格
const loadTodayPrices = async () => {
  try {
    const response = await itemsAPI.getItems({
      page: 1,
      pageSize: 5,
      status: 'active'
    })

    const itemList = response.list || response.data || response || []
    
    todayPrices.value = itemList.map(item => ({
      id: item.id,
      name: item.name,
      category: item.category || '其他',
      price: item.pricePerUnit || 0,
      unit: item.unit || 'kg'
    }))
  } catch (error) {
    console.error('加载价格信息失败:', error)
    ElMessage.error('加载价格信息失败')
  }
}

// 方法
const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    confirmed: 'primary',
    in_progress: 'info',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待确认',
    confirmed: '已确认',
    in_progress: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || '未知'
}

const viewOrder = (order) => {
  router.push(`/customer/orders?orderId=${order.id}`)
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  const date = new Date(dateTimeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

onMounted(() => {
  loadStats()
  loadRecentOrders()
  loadTodayPrices()
})
</script>

<style scoped>
.customer-dashboard {
  padding: 0;
}

.welcome-card {
  margin-bottom: 24px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.welcome-card :deep(.el-card__body) {
  background: transparent;
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-text h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.welcome-text p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

.highlight {
  color: #FFD700;
  font-weight: bold;
  font-size: 18px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}

.stats-card {
  border-radius: 12px;
}

.stats-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stats-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stats-icon.orders {
  background: linear-gradient(135deg, #409EFF 0%, #66B2FF 100%);
}

.stats-icon.pending {
  background: linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%);
}

.stats-icon.earnings {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
}

.stats-info h3 {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.stats-info p {
  margin: 0 0 4px 0;
  color: #666;
  font-size: 14px;
}

.stats-change {
  font-size: 12px;
  color: #999;
}

.stats-change.positive {
  color: #67C23A;
}

.content-section {
  margin-bottom: 24px;
}

.orders-card,
.price-card {
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.orders-table {
  overflow-x: auto;
}

.orders-table :deep(.el-table__body) {
  font-size: 14px;
}

.orders-table :deep(.el-table__header) {
  font-size: 14px;
}

.orders-table :deep(.el-table__cell) {
  font-size: 14px;
}

.orders-table :deep(.el-button) {
  font-size: 14px;
}

.orders-table :deep(.el-tag) {
  font-size: 12px;
}

.price-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.item-category {
  font-size: 12px;
  color: #666;
}

.item-price {
  text-align: right;
}

.price {
  font-size: 16px;
  font-weight: bold;
  color: #67C23A;
}

.unit {
  font-size: 12px;
  color: #999;
}

.bottom-section {
  margin-bottom: 24px;
}

.actions-card,
.tips-card {
  border-radius: 12px;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e6e6e6;
}

.action-item:hover {
  background: #f8f9fa;
  border-color: #409EFF;
  transform: translateY(-2px);
}

.action-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.action-icon.browse {
  background: linear-gradient(135deg, #409EFF 0%, #66B2FF 100%);
}

.action-icon.create {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
}

.action-icon.track {
  background: linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%);
}

.action-icon.profile {
  background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
}

.action-text h4 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 16px;
}

.action-text p {
  margin: 0;
  color: #666;
  font-size: 12px;
}

.eco-tips {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #67C23A;
}

.tip-item span {
  font-size: 14px;
  color: #333;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .quick-actions {
    grid-template-columns: 1fr;
  }
}

/* 平板设备 */
@media (max-width: 992px) {
  .price-card,
  .tips-card {
    margin-top: 24px;
  }
  
  /* 隐藏预约时间列 */
  .orders-table :deep(.hide-on-tablet) {
    display: none;
  }
}

/* 移动设备 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .welcome-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .content-section {
    margin-bottom: 16px;
  }
  
  .orders-card,
  .price-card,
  .actions-card,
  .tips-card {
    margin-bottom: 16px;
  }
  
  /* 隐藏回收站点列 */
  .orders-table :deep(.hide-on-mobile) {
    display: none;
  }
  
  /* 调整表格按钮大小 */
  .orders-table :deep(.el-button) {
    padding: 4px 8px;
    font-size: 13px;
  }
  
  .orders-table :deep(.el-table__cell) {
    font-size: 13px;
  }
  
  /* 调整卡片内边距 */
  .orders-card :deep(.el-card__body),
  .price-card :deep(.el-card__body),
  .actions-card :deep(.el-card__body),
  .tips-card :deep(.el-card__body) {
    padding: 12px;
  }
  
  .card-header {
    font-size: 14px;
  }
  
  .card-header .el-button {
    font-size: 12px;
    padding: 4px 8px;
  }
  
  /* 调整快捷操作图标大小 */
  .action-icon {
    width: 40px;
    height: 40px;
  }
  
  .action-icon .el-icon {
    font-size: 24px;
  }
  
  .action-text h4 {
    font-size: 14px;
  }
  
  .action-text p {
    font-size: 11px;
  }
}

/* 小屏手机 */
@media (max-width: 480px) {
  .welcome-text h2 {
    font-size: 20px;
  }
  
  .welcome-text p {
    font-size: 14px;
  }
  
  .stats-info h3 {
    font-size: 18px;
  }
  
  .stats-info p {
    font-size: 12px;
  }
  
  .price-item {
    padding: 10px;
  }
  
  .item-name {
    font-size: 12px;
  }
  
  .item-category {
    font-size: 11px;
  }
  
  .price {
    font-size: 14px;
  }
  
  .unit {
    font-size: 11px;
  }
  
  /* 确保表格在小屏幕上可以滚动 */
  .orders-card :deep(.el-card__body) {
    overflow-x: auto;
    padding: 8px;
  }
  
  /* 调整表格列最小宽度 */
  .orders-table :deep(.el-table__cell) {
    padding: 8px 4px;
    font-size: 12px;
  }
  
  .orders-table :deep(.el-button) {
    font-size: 12px;
  }
  
  /* 调整快捷操作为单列 */
  .quick-actions {
    grid-template-columns: 1fr;
  }
  
  .action-item {
    padding: 12px;
  }
}
</style>
